package cn.triedblog.dto;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import com.fasterxml.jackson.annotation.JsonIgnore;

import cn.triedblog.entity.SystemRole;
import cn.triedblog.entity.SystemUser;

/**
 * 登录用户类包装
 * 
 * @author 偶尔有点困
 * @date 2018年5月18日
 */
public class SystemUserLogin extends SystemUser implements UserDetails {

	private static final long serialVersionUID = -2837529240203883169L;

	private Set<SystemRole> roles;

	private Set<String> permissions;

	public Set<SystemRole> getRoles() {
		return roles;
	}

	public void setRoles(Set<SystemRole> roles) {
		this.roles = roles;
	}

	public Set<String> getPermissions() {
		return permissions;
	}

	public void setPermissions(Set<String> permissions) {
		this.permissions = permissions;
	}

	@JsonIgnore
	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		Collection<GrantedAuthority> collection = new HashSet<>();
		if (!CollectionUtils.isEmpty(roles)) {
			roles.parallelStream().forEach(role -> {
				if (role.getName().startsWith("ROLE_")) {
					collection.add(new SimpleGrantedAuthority(role.getName()));
				} else {
					collection.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));
				}
			});
		}

		if (!CollectionUtils.isEmpty(permissions)) {
			permissions.parallelStream().forEach(per -> {
				collection.add(new SimpleGrantedAuthority(per));
			});
		}

		return collection;
	}

	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	@Override
	public boolean isEnabled() {
		return true;
	}

}
